package ar.edu.uba.fi.jmit.mailvisualizer;

import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import ar.edu.uba.fi.jmit.integrationcommons.Event;
import ar.edu.uba.fi.jmit.integrationcommons.EventPriority;
import ar.edu.uba.fi.jmit.mailvisualizer.ResourceProperties.Property;
import ar.edu.uba.fi.jmit.receiver.ReceiverObserver;

public class MailVisualizerManager implements ReceiverObserver {

	private final Logger logger = Logger.getLogger(this.getClass());

	private static MailVisualizerManager instance = new MailVisualizerManager();

	private MailVisualizerManager() {
		super();
	}

	public static MailVisualizerManager getInstance() {
		return instance;
	}

	@Override
	public void onRecivedEvent(Event event) {
		logger.debug("received event in mail visualizer");
		if(isAlert(event)) {
			try {
				this.sendMail(event);
			} catch (MessagingException e) {
				logger.error("There was an error while sending an email with mailVisualizer", e);
			}
		}
	}

	private void sendMail(Event event) throws MessagingException {
		logger.debug("sending mail...");
		Properties props = this.getConfigurations();
		Session session = Session.getDefaultInstance(props, null);
		session.setDebug(true);

		Message msg = new MimeMessage(session);

		InternetAddress addressFrom = new InternetAddress(ResourceProperties.getProperty("mailFrom"));
		msg.setFrom(addressFrom);

		InternetAddress[] addressTo = getAddressesFor();
		
		msg.setSubject("Alert in JMit. Please review the application");
		msg.setContent(getMailContent(event), "text/plain");
		Transport transport = session.getTransport();
		transport.connect(ResourceProperties.getProperty("smtp"), Integer.valueOf(ResourceProperties.getProperty("port")), ResourceProperties.getProperty("mailFrom"), ResourceProperties.getProperty("password"));
		transport.sendMessage(msg,addressTo);
		transport.close();

	}

	private InternetAddress[] getAddressesFor() {
		String addressesToString = ResourceProperties.getProperty("mailsTo");
		String[] addressesTo = addressesToString.replaceAll(",", ";").split(";");
		InternetAddress[] addresses = new InternetAddress[addressesTo.length];
		int i = 0;
		for(String address:addressesTo) {
			try {
				addresses[i] = new InternetAddress(address.trim());
			} catch (AddressException e) {
				logger.error("Error creating internet address for mail " + address, e);
			}
			i++;
		}
		return addresses;
	}

	private Properties getConfigurations() {
		Properties properties = new Properties();
		List<Property> configs = ResourceProperties.getInstance().getConfigurationValues();
		for(Property prop:configs) {
			properties.put(prop.getKey(), prop.getValue());
		}
		return properties;
	}

	private String getMailContent(Event event) {
		StringBuffer buff = new StringBuffer();
		buff.append("\tSource: " + event.getSource() + "\n");
		buff.append("\tPriority: " + event.getPriority() + "\n");
		for(String key:event.getData().keySet()) {
			buff.append("\t" + key + ":" + event.getData().get(key) + "\n");
		}
		return buff.toString();
	}

	private boolean isAlert(Event event) {
		return event.getPriority().equals(EventPriority.ALERT);
	}

}
